import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { Observable, throwError } from 'rxjs'
import { map, catchError } from 'rxjs/operators'

import { COMB_URL } from 'app/utils/contraints'
import { IDepositQuery, IDeposit, IDepositCollection } from '@shared/interfaces/deposit'
import { IGenericPagination } from '@shared/interfaces/pagination'
import { preProcessParams, encodeParams } from '@shared/decorators'

@Injectable()
export class DepositService {
  constructor(private http: HttpClient) {}

  @preProcessParams()
  @encodeParams()
  getList(params: IDepositQuery, str?: string): Observable<IGenericPagination<IDeposit>> {
    const url = `${COMB_URL}/camel/settle/deposits?${str}`
    return this.http.get<IGenericPagination<IDeposit>>(url)
  }

  getOne(id: string): Observable<IDeposit> {
    const url = `${COMB_URL}/camel/settle/deposit/${id}`
    return this.http.get<IDeposit>(url)
  }

  createCollection(data: IDepositCollection): Observable<boolean> {
    const url = `${COMB_URL}/camel/settle/deposit`

    return this.http
      .post(url, data, {
        observe: 'response',
      })
      .pipe(
        map(resp => {
          const { status } = resp
          if (status === 200) {
            return true
          }

          throwError(resp)
        }),
        catchError(error => {
          return throwError(error)
        }),
      )
  }

  createReturn(data: IDepositCollection): Observable<boolean> {
    const url = `${COMB_URL}/camel/settle/restitution`

    return this.http
      .post(url, data, {
        observe: 'response',
      })
      .pipe(
        map(resp => {
          const { status } = resp
          if (status === 200) {
            return true
          }

          throwError(resp)
        }),
        catchError(error => {
          return throwError(error)
        }),
      )
  }

  stopCollectingDeposit(id: string): Observable<boolean> {
    const url = `${COMB_URL}/camel/settle/deposit/${id}/end`

    return this.http
      .post(
        url,
        {},
        {
          observe: 'response',
        },
      )
      .pipe(
        map(resp => {
          const { status } = resp
          if (status === 200) {
            return true
          }

          throwError(resp)
        }),
        catchError(error => {
          return throwError(error)
        }),
      )
  }

  getDepositAmtOfStore(intStoreID: string): Observable<IDepositCollection> {
    const url = `${COMB_URL}/camel/settle/depositamt/${intStoreID}`
    return this.http.get<IDepositCollection>(url)
  }
}
